package com.fancy.learncenter.common;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.fancy.learncenter.activity.LoginActivity;
import com.fancy.learncenter.activity.MainActivity;
import com.fancy.learncenter.activity.PersonInfoActivity;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.PersonCenterDataBean;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.ta.utdid2.device.UTDevice;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.yixia.camera.VCamera;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import fancy.hyypaysdk.pay.alipay.AliPayUtils;
import io.rong.imkit.DefaultExtensionModule;
import io.rong.imkit.IExtensionModule;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongExtension;
import io.rong.imkit.RongExtensionManager;
import io.rong.imkit.RongIM;
import io.rong.imkit.model.UIConversation;
import io.rong.imkit.plugin.IPluginModule;
import io.rong.imkit.plugin.ImagePlugin;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import okhttp3.OkHttpClient;

import static io.rong.imkit.utils.SystemUtils.getCurProcessName;

/**
 * Created by Hyy on 2016/9/22.
 */
public class MyApplication extends Application {

    public static Context context = null;
    public static String VIDEO_PATH = Environment.getExternalStorageDirectory().getPath() + "/lyVideo/";
    private static MyApplication instance;
    //(易沟通状态 0:没有 1:有效 2:试用 3:过期)
    public static String is_device = "";
    public static String token = "";
    public static String userId = "";
    public static String utdid = "";

    public static String WX_LOGIN_CODE = "";

    //融云是否登录
    public static boolean ryIsLogin = false;

    public String getWX_LOGIN_CODE() {

        String code = WX_LOGIN_CODE;
        WX_LOGIN_CODE = "";
        return code;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        RongIM.init(this);

        WeiXinUtils.getInstance().init(getApplicationContext());
//
//        connect("saa7A4tk+LkNlDGSR9hHK3BsZOtY0QzJzWS5w/fZ4PzUsTQNzrb1aI/R17mXVLcd0MijHva5UxlxYvwsFYA25g==");//666666
//
//        //设置消息携带用户信息
//        RongIM.getInstance().setMessageAttachedUserInfo(true);

        context = getApplicationContext();

        ToastUtil.initToast(getApplicationContext());

//        //微信
//        PlatformConfig.setWeixin("wxd422caeaa8ad29c5", "3820b5f7985c8ba0a30c123f619d8262");
//        //新浪微博
//        PlatformConfig.setSinaWeibo("600049747", "04b48b094faeb16683c32669824ebdad");
//        //QQ
//        PlatformConfig.setQQZone("1105746474", "3inyZO7bl8nK9SaC");
        initFresco();
        //初始化视频录制
        initVideoRecorder();


        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());

        //获取一次定位结果：
        mLocationClient.setLocationListener(mLocationListener);


        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);


        if (null != mLocationClient) {
            mLocationClient.setLocationOption(option);
            //mLocationClient，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }


        UMConfigure.init(this, "5b31b525f43e4869a400000c", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, null);
        UMConfigure.setLogEnabled(true);

        RongIM.init(this);
        MobclickAgent.setCatchUncaughtExceptions(true);

        utdid = UTDevice.getUtdid(this);

        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String s) {

                LogUtil.MyLog("setUserInfoProvider", "=======setUserInfoProvider==" + s);

                getDatas(s);

                return null;

            }
        }, false);

        setMyExtensionModule();

        RongIM.setConnectionStatusListener(new RongIMClient.ConnectionStatusListener() {
            @Override
            public void onChanged(ConnectionStatus connectionStatus) {
                switch (connectionStatus) {
                    case CONNECTED://连接成功。

                        break;
                    case DISCONNECTED://断开连接。

                        break;
                    case CONNECTING://连接中。

                        break;
                    case NETWORK_UNAVAILABLE://网络不可用。

                        break;
                    case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线
                        MyApplication.ryIsLogin = false;
//                        SPUtils.putToken("");
//                        SPUtils.putUserID("");
//
//                        MyApplication.userId = "";
//
//                        MyApplication.token = "";
//
//                        ToastUtil.show("您的账号在其他设备上登录");
                        break;
                }
            }
        });
        RongIM.setConversationListBehaviorListener(new RongIM.ConversationListBehaviorListener() {
            @Override
            public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String s) {

                Intent intent = new Intent(context, PersonInfoActivity.class);
                intent.putExtra("userId", s);
                startActivity(intent);


                return true;
            }

            @Override
            public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String s) {
                return false;
            }

            @Override
            public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) {
                return false;
            }

            @Override
            public boolean onConversationClick(Context context, View view, UIConversation uiConversation) {
                return false;
            }
        });


        RongIM.getInstance().setConversationClickListener(new RongIM.ConversationClickListener() {
            @Override
            public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {

                if (userInfo != null && !TextUtils.isEmpty(userInfo.getUserId())) {
                    Intent intent = new Intent(context, PersonInfoActivity.class);

                    intent.putExtra("userId", userInfo.getUserId());

                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    context.startActivity(intent);
                }


                return true;
            }

            @Override
            public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {
                return false;
            }

            @Override
            public boolean onMessageClick(Context context, View view, Message message) {
                return false;
            }

            @Override
            public boolean onMessageLinkClick(Context context, String s, Message message) {
                return false;
            }

            @Override
            public boolean onMessageLongClick(Context context, View view, Message message) {
                return false;
            }
        });

    }

    private void getDatas(String userId) {
        Map map = new HashMap();
        map.put("userId", "" + userId);
        map.put("myId", "" + MyApplication.userId);
        map.put("token", "" + MyApplication.token);
        HttpMehtod.getInstance().baseDetail(map, new IdeaObserver<BaseDataBean<PersonCenterDataBean>>() {

            @Override
            public void onSuccess(BaseDataBean<PersonCenterDataBean> listBaseDataBean) {

                /**
                 * 刷新用户缓存数据。
                 *
                 * @param userInfo 需要更新的用户缓存数据。
                 */

                if (TextUtils.isEmpty(listBaseDataBean.getData().getNick_name())) {
                    listBaseDataBean.getData().setNick_name(listBaseDataBean.getData().getId());
                }

                if (TextUtils.isEmpty(listBaseDataBean.getData().getImgsrc())) {
                    listBaseDataBean.getData().setImgsrc("");
                }


                UserInfo userInfo = new UserInfo(listBaseDataBean.getData().getId(), listBaseDataBean.getData().getNick_name(), Uri.parse(listBaseDataBean.getData().getImgsrc()));

                RongIM.getInstance().refreshUserInfoCache(userInfo);

            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    public void setMyExtensionModule() {
//        List<IExtensionModule> moduleList = RongExtensionManager.getInstance().getExtensionModules();
//        IExtensionModule defaultModule = null;
//        if (moduleList != null) {
//            for (IExtensionModule module : moduleList) {
//                if (module instanceof DefaultExtensionModule) {
//                    defaultModule = module;
//                    break;
//                }
//            }
//            if (defaultModule != null) {
//                RongExtensionManager.getInstance().unregisterExtensionModule(defaultModule);
//
//            }
//        }

        RongExtensionManager.getInstance().getExtensionModules().clear();

        LogUtil.MyLog("RongExtensionManager", "asdasdasRongExtensionManagerd" + RongExtensionManager.getInstance().getExtensionModules().size());
        RongExtensionManager.getInstance().registerExtensionModule(new MyExtensionModule());

    }

//    public class MyPlugin implements ImagePlugin {
//        @Override
//        public Drawable obtainDrawable(Context context) {
//            return null;
//        }
//
//        @Override
//        public String obtainTitle(Context context) {
//            return null;
//        }
//
//        @Override
//        public void onClick(Fragment fragment, RongExtension rongExtension) {
//
//        }
//
//        @Override
//        public void onActivityResult(int i, int i1, Intent intent) {
//
//        }
//    }

    public class MyExtensionModule extends DefaultExtensionModule {
//        private MyPlugin myPlugin;

        @Override
        public List<IPluginModule> getPluginModules(Conversation.ConversationType conversationType) {
            List<IPluginModule> pluginModules = new ArrayList<>();
            pluginModules.add(new ImagePlugin());
            return pluginModules;
        }
    }


    public static double longitude = 0;
    public static double latitude = 0;


    AMapLocationClientOption option = new AMapLocationClientOption();


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            longitude = aMapLocation.getLongitude();
            latitude = aMapLocation.getLatitude();
            LogUtil.MyLog("mLocationListener", aMapLocation.getLongitude() + "=======" + aMapLocation.getLatitude());
        }
    };

    private void initVideoRecorder() {
        VIDEO_PATH += String.valueOf(System.currentTimeMillis());
        File file = new File(VIDEO_PATH);
        if (!file.exists()) file.mkdirs();
        //设置视频缓存路径
        VCamera.setVideoCachePath(VIDEO_PATH);
        // 开启log输出,ffmpeg输出到logcat
        VCamera.setDebugMode(true);
        // 初始化拍摄SDK，必须
        VCamera.initialize(this);
    }

    private void initFresco() {
        Fresco.initialize(this);
    }

    public Context getContext() {
        if (context == null) {
            context = this.getApplicationContext();
        }
        return context;
    }

    /**
     * 用token连接融云服务器
     * <p>
     * 一般在登录的时候后台返回token 登录成功调用此方法
     */
    private void connect(String token) {
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {
            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String userid) {
                    RongIM.getInstance().setCurrentUserInfo(new UserInfo(userid, "阿斯顿发", null));
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }

    public static MyApplication getInstance() {

        if (instance == null) {
            instance = new MyApplication();
        }
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static String getAnroidId() {
//        String macAddress = " ";
//        WifiManager wifiManager =
//                (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//        WifiInfo info = (null == wifiManager ? null : wifiManager.getConnectionInfo());
//
//        if (!wifiManager.isWifiEnabled()) {
//            //必须先打开，才能获取到MAC地址
//            wifiManager.setWifiEnabled(true);
//            wifiManager.setWifiEnabled(false);
//        }
//        if (null != info) {
//            macAddress = info.getMacAddress();
//        }
        return MyApplication.utdid;
    }
}
